package fmi.chesstern.ui.gui;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import fmi.chesstern.game.BoardField;
import fmi.chesstern.game.GameState;
import fmi.chesstern.game.Move;
import fmi.chesstern.game.events.GameStateChangedEvent;
import fmi.chesstern.game.events.GameStateChangedListener;
import fmi.events.EventDispatcher;

public class GUIBoardState {
	private GameState gameState;
	private BoardField selectedField;
	private Set<BoardField> targetFields;
	private EventDispatcher<GameStateChangedEvent, GameStateChangedListener> dispatcher;
	
	public void addGameStateChangedListener(GameStateChangedListener listener) {
		dispatcher.addEventListener(listener);
	}
	
	public void removeGameStateChangedListener(GameStateChangedListener listener) {
		dispatcher.removeEventListener(listener);
	}
	
	public GUIBoardState(GameState gameState) {
		this.gameState = gameState;
		this.selectedField = null;
		this.targetFields = new HashSet<BoardField>();
		this.dispatcher = new EventDispatcher<GameStateChangedEvent, GameStateChangedListener>();
		
		gameState.addGameStateChangedListener(new GameStateChangedListener() {			
			@Override
			public void handleEvent(GameStateChangedEvent event) {
				dispatcher.dispatchEvent(event);
			}
		});
	}

	public BoardField getSelectedField() {
		return selectedField;
	}

	public void setSelectedField(BoardField selectedField) {
		this.selectedField = selectedField;
		
		targetFields.clear();
		
		if (selectedField != null && gameState.getGameBoardState().getPieceAt(selectedField) != null) {
			for (Move move : gameState.getGameBoardState().getPieceAt(selectedField).getValidMoves(
					gameState.getGameBoardState(), selectedField)) {
				targetFields.add(move.getTo());
			}
		}
		
		dispatcher.dispatchEvent(new GameStateChangedEvent(this));
	}

	public GameState getGameState() {
		return gameState;
	}

	public Set<BoardField> getTargetFields() {
		return Collections.unmodifiableSet(targetFields);
	}
}
